package com.jwater.console.common;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jwater.console.model.Result;
import com.jwater.console.service.ConsoleService;

import jwater.com.alibaba.fastjson.JSON;
import jwater.org.springframework.util.StringUtils;

/**
 * @description: 拦截器，拦截所有的请求，进行权限校验
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class CommonInterceptor implements HandlerInterceptor {
    protected static Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);
    private boolean checkLogin = false;
    private ConsoleService consoleService;

    public CommonInterceptor(boolean checkLogin, ConsoleService consoleService) {
        this.checkLogin = checkLogin;
        this.consoleService = consoleService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!checkLogin) {
            return true;
        }
        // 以下url直接通过
        String url = request.getRequestURI();
        if (url.endsWith("/login") || url.endsWith("/upload/") || url.endsWith("/uploadFile/")
                || url.endsWith("/downLogContent") || url.endsWith("/downCmdJvmInfo")
                || url.endsWith("/downFile") || !url.startsWith("/jwater/console")) {
            return true;
        }
        // 权限校验，从header中获取token进行校验
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token) || !consoleService.existToken(token)) {
            try {
                PrintWriter pw = response.getWriter();
                response.setHeader("Content-Type", "application/json;charset=UTF-8");
                response.sendError(HttpStatus.OK.value(), "未登录！");
                pw.write(JSON.toJSONString(Result.notLogin("未登录！")));
            } catch (IOException e) {
                logger.error(e.toString(), e);
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
